package com.wqj.kyee.gps.bluetooth.server;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.wqj.kyee.gps.bluetooth.ble.BluetoothLeService;

import java.io.ByteArrayInputStream;

public class ConnectionService extends Service implements ConnectionManager.ConnectStateListener{

	private HandlerThread connectThread;
	private Handler connectThreadHandler;
	private ConnectionManager connectionManager;
	private HandlerThread readThread;
	private Handler readThreadHandler;
	private static final int CONNECTREQUEST = 1;
	private static final int READREQUEST = 2;

	private static final String TAG = ConnectionService.class.getSimpleName();


	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		initBackThread();
		connectionManager =ConnectionManager.getInstance();

		SharedPreferences sharedPreferences = getSharedPreferences("bt-gps", Context.MODE_PRIVATE);
		String bltAdress = sharedPreferences.getString("blt-adress", "");
		Boolean isAutoConnect = sharedPreferences.getBoolean("auto-connect", false);

		if (isAutoConnect && bltAdress != "") {
			BluetoothAdapter bluetoothAdapter =  BluetoothAdapter.getDefaultAdapter();
			BluetoothDevice blt = bluetoothAdapter.getRemoteDevice(bltAdress);
			connectionManager.init(blt);
			connectThreadHandler.sendEmptyMessage(CONNECTREQUEST);
		}

		registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

		Log.e(TAG, "onCreate");
	}
	@SuppressLint("NewApi") @Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub

		String value = intent.getStringExtra("key");
		if("connect".equals(value)){
			BluetoothDevice bluetoothDevice = intent.getParcelableExtra("btdevice");
			if(null != bluetoothDevice){
				connectionManager.init(bluetoothDevice);
				connectThreadHandler.sendEmptyMessage(CONNECTREQUEST);
			}
		}

		if("disconnect".equals(value)){
			connectionManager.cancel();
		}

		if("read".equals(value)){
			if(connectionManager.isConnected()){
				readThreadHandler.sendEmptyMessage(READREQUEST);
			}
		}

//		
		Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
//		builder.setSmallIcon(R.drawable.ic_launcher);
//        builder.setTicker("12222");
//        builder.setWhen(System.currentTimeMillis());
//        builder.setContentTitle(getString(R.string.app_name));
//        builder.setContentText("123123");
//		Intent nfIntent = new Intent(this, MainActivity.class);
//		builder.setContentIntent(PendingIntent.
//		getActivity(this, 0, nfIntent, 0)); // 设置上下文内容
		Notification notification = builder.build(); // 获取构建好的Notification
		notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
		startForeground(Integer.MAX_VALUE, notification);
		return super.onStartCommand(intent, flags, startId);
	}
	
	private void initBackThread(){
		connectThread = new HandlerThread("connect_thread");
		connectThread.start();
		
		readThread = new HandlerThread("read_thread");
		readThread.start();
		connectThreadHandler = new Handler(readThread.getLooper()){
			@Override
			public void handleMessage(Message msg) {
				int what = msg.what;
				switch (what) {
				case CONNECTREQUEST:
					connectionManager.setConnectStateListener(ConnectionService.this);
					connectionManager.connect();
					break;

				default:
					break;
				}
			}
		};
		
		readThreadHandler = new Handler(readThread.getLooper()){
			@Override
			public void handleMessage(Message msg) {
				int what = msg.what;
				switch (what) {
				case READREQUEST:
					connectionManager.read();
					break;
				default:
					break;
				}
			}
		};

	}

	@Override
	public void connectSuccess(BluetoothDevice bluetoothDevice) {
		SharedPreferences sp = getSharedPreferences("bt-gps", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("blt-adress", bluetoothDevice.getAddress());
		editor.commit();

		if(connectionManager.isConnected()){
			readThreadHandler.sendEmptyMessage(READREQUEST);
		}

	}
	@Override
	public void disconnectSuccess(BluetoothDevice bluetoothDevice) {

	}

	@Override
	public void connectFail(BluetoothDevice bluetoothDevice) {

	}


	private static IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
		intentFilter.addAction(BluetoothLeService.ACTION_WRITE_SUCCESSFUL);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_NO_DISCOVERED);
		return intentFilter;
	}

	String previousLine = "";
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
				Log.e(TAG, "ACTION_GATT_CONNECTED");
			} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
				Log.e(TAG, "ACTION_GATT_DISCONNECTED");
			} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
				Log.e(TAG, "ACTION_GATT_SERVICES_DISCOVERED");
			}else if (BluetoothLeService.ACTION_GATT_SERVICES_NO_DISCOVERED.equals(action)){
				Log.e(TAG, "ACTION_GATT_SERVICES_NO_DISCOVERED");
			}else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
				//Log.e(TAG, "ACTION_DATA_AVAILABLE");

				byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
				ByteArrayInputStream bais = new ByteArrayInputStream(data);

				String line = previousLine;

				while (bais.available() > 0) {
					int tmp = bais.read();
					line += (char) tmp;

					if (tmp == '\n') {
						if (line.contains("RMC")) {
							Log.e(TAG, "Found RMC");
						}
						connectionManager.parseLine(line);

						line = "";
					}
				}

				if (!line.isEmpty()) {
					previousLine = line;
				}

				//displayData(intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA));
			}else if (BluetoothLeService.ACTION_WRITE_SUCCESSFUL.equals(action)) {

			}

		}
	};
}
